<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-01 10:07:47
 * @LastEditTime: 2024-02-04 10:43:48
-->
<script lang="ts" setup name="DatasourceModal">
import { datasourceApi } from '@/MainApp/apis/datasource'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formKey: {
    type: Object,
    default: () => { }
  },
  editData: {
    type: Object,
    default: () => null
  }
})
const emits = defineEmits<{
  (e: 'update:visible', bool: boolean): void
  (e: 'dataChange'): void
}>()

const { dialog, t } = useConfig()
const { lenName, lenContent } = useLength()
const { msgError } = useMessage()
// 新增、修改
const placeholder = {
  name: '请输入连接名称',
  type: '请选择数据库类型',
  ip: '请输入ip地址',
  port: '请输入端口',
  username: '请输入用户名',
  password: '请输入密码',
  schemaName: '请选择数据库名称',
  remark: '请输入描述'
  // driverClassName: '驱动类名'
}

const datasourceState = reactive({
  title: '新增数据源',
  loading: false,
  form: props.formKey
    ? { ...props.formKey }
    : {
        name: '',
        type: '',
        ip: '',
        port: '',
        username: '',
        password: '',
        schemaName: '',
        remark: ''
        // driverClassName: ''
      }
})
const datasourceRules = {
  name: [{ required: true, message: placeholder.name, trigger: 'blur' }],
  type: [{ required: true, message: placeholder.type, trigger: 'change' }],
  ip: [{ required: true, message: placeholder.ip, trigger: 'blur' }],
  username: [
    { required: true, message: placeholder.username, trigger: 'blur' }
  ],
  port: [{ required: true, message: placeholder.port, trigger: 'blur' }],
  password: [
    { required: true, message: placeholder.password, trigger: 'blur' }
  ],
  schemaName: [
    { required: true, message: placeholder.schemaName, trigger: 'change' }
  ]
}
const datasourceRef = ref()
const dVisible = ref(false)
const databaseType = ref<any>([])
const typeList = ref<any>([])
const handleClose = () => {
  emits('update:visible', false)
  datasourceState.loading = false
  datasourceRef.value?.resetFields()
  datasourceState.form = { ...props.formKey }
}

const handConfirm = () => {
  datasourceRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      datasourceState.loading = true
      const { msg, success } = props.editData
        ? await datasourceApi.updateDatasource(datasourceState.form)
        : await datasourceApi.addDatasources(datasourceState.form)
      if (success) {
        handleClose()
        emits('dataChange')
      }
      else {
        msgError(msg)
      }

      datasourceState.loading = false
    }
  })
}
const getDatabase = async () => {
  // const { success, data } = await datasourceApi.getDatabaseType()
  // if (success)

  databaseType.value = [
    { label: 'MYSQL', name: 'MYSQL' },
    { label: 'Postgres', name: 'POSTGRES' },
    { label: 'Oracle', name: 'ORACLE' },
    { label: 'SQLServer', name: 'MSSQL_SERVER' }
  ]
}
getDatabase()
watch(
  () => props.visible,
  (bool: boolean) => {
    dVisible.value = bool
    if (bool && props.editData) {
      datasourceState.form = { ...props.editData }
      datasourceState.title = '编辑数据源'
      getALLCurrent()
    }
    else {
      datasourceState.title = '新增数据源'
    }
  }
)
const loadingSchema = ref(false)
const changeForm = () => {
  datasourceState.form.schemaName = ''
  typeList.value = []
  getALLCurrent()
}
const getALLCurrent = async () => {
  if (
    datasourceState.form?.type
    && datasourceState.form?.ip
    && datasourceState.form?.port
    && datasourceState.form?.username
    && datasourceState.form?.password
  ) {
    loadingSchema.value = true
    const { data, success, msg } = await datasourceApi.getALLCurrent(
      datasourceState.form
    )
    if (success)
      typeList.value = data
    else msgError(msg)
    loadingSchema.value = false
  }
}
</script>

<template>
  <el-dialog
    v-model="dVisible"
    :title="datasourceState.title"
    draggable
    :width="dialog.l"
    :close-on-click-modal="false"
    align-center
    append-to-body
    @closed="handleClose"
  >
    <el-form
      ref="datasourceRef"
      :model="datasourceState.form"
      :rules="datasourceRules"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="连接名称" prop="name">
        <el-input
          v-model.trim="datasourceState.form.name"
          :maxlength="lenName"
          :placeholder="placeholder.name"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item label="数据库类型" prop="type">
        <el-select
          v-model="datasourceState.form.type"
          :placeholder="placeholder.type"
          clearable
          @change="changeForm"
        >
          <el-option
            v-for="item in databaseType"
            :key="item.name"
            :label="item.label"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="ip" prop="ip">
            <el-input
              v-model.trim="datasourceState.form.ip"
              clearable
              :maxlength="lenName"
              :placeholder="placeholder.ip"
              show-word-limit
              @blur="changeForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="端口" prop="port">
            <el-input
              v-model="datasourceState.form.port"
              clearable
              :maxlength="lenName"
              :placeholder="placeholder.port"
              show-word-limit
              @blur="changeForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model.trim="datasourceState.form.username"
              clearable
              :maxlength="lenName"
              :placeholder="placeholder.username"
              show-word-limit
              @blur="changeForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model.trim="datasourceState.form.password"
              clearable
              :maxlength="lenName"
              type="password"
              :placeholder="placeholder.password"
              tabindex="2"
              autocomplete="new-password"
              show-password
              @blur="changeForm"
            >
              <template #prefix>
                <el-icon size="18">
                  <IkSvgIcon name="iksvg_suoping" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item class="col-cen" label="数据库名称" prop="schemaName">
            <el-select
              v-model="datasourceState.form.schemaName"
              v-loading="loadingSchema"
              clearable
              :placeholder="placeholder.schemaName"
            >
              <el-option
                v-for="item in typeList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="驱动类名" prop="driverClassName">
        <el-input
          v-model.trim="datasourceState.form.driverClassName"
          clearable
          :maxlength="lenName"
          :placeholder="placeholder.driverClassName"
          show-word-limit
        />
      </el-form-item> -->
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model.trim="datasourceState.form.remark"
          clearable
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 4 }"
          :maxlength="lenContent"
          :placeholder="placeholder.remark"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button bg text @click="handleClose">
        {{ t('action.cancel') }}
      </el-button>
      <el-button type="primary" :loading="datasourceState.loading" @click="handConfirm">
        {{ t('action.sure') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.col-cen {
  :deep(.el-form-item__content) {
    flex-wrap: nowrap !important;
  }

  .col-btn {
    margin-left: 10px;
  }
}

.data-s {
  padding: 15px 24px;
}
</style>
